package com.mika.music.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mika.music.constants.Constant;
import com.mika.music.model.Comment;
import com.mika.music.model.Comments;
import com.mika.music.model.Music;
import com.mika.music.model.User;
import com.mika.music.service.CommentService;
import com.mika.music.service.MusicService;
import com.mika.music.utils.ResponseBodyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private MusicService musicService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    // 如果某一首歌的评论非常多，达到了 10w 条，那就可以单独为这首歌创建一张表
    @RequestMapping("/addComment")
    public ResponseBodyMessage<Boolean> addComment(@RequestParam String commentStr, @RequestParam String songName, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            return new ResponseBodyMessage<>(-2, "您尚未登录!", false);
        }
        if (!StringUtils.hasLength(commentStr) || !StringUtils.hasLength(songName)) {
            return new ResponseBodyMessage<>(-1, "评论内容不能为空!", false);
        }
        if (commentStr.length() > 50) {
            return new ResponseBodyMessage<>(-1, "评论内容大于 50 字，评论失败", false);
        }
        // 先根据歌名找到歌曲
        // TODO 先去 redis 中根据歌曲名查找到歌曲 ID，然后再通过 ID 查找到歌曲详情
        String musicname = "musicName:" + songName;
        String musicId = stringRedisTemplate.opsForValue().get(musicname);
        Music music = null;
        if (StringUtils.hasLength(musicId)) {
            try {
                String musicInfoKey = "music:info:" + musicId;
                music = objectMapper.readValue(stringRedisTemplate.opsForValue().get(musicInfoKey), Music.class);
                User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
                Comment comment = new Comment(user.getId(), music.getId(), commentStr);
                // 新增评论
                Integer result = commentService.addComment(comment);
                if (result > 0) {
                    return new ResponseBodyMessage<>(200, null, true);
                } else {
                    return new ResponseBodyMessage<>(-1, "评论失败，请联系管理员", false);
                }


            } catch (JsonProcessingException e) {
                log.error(e.getMessage());
            }
        } else {
            // 到这里说明 redis 没有对应歌曲数据
            music = musicService.getSongByName(songName);
        }

        if (music == null) {
            return new ResponseBodyMessage<>(-1, "你想评论的歌曲不存在", false);
        }
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        Comment comment = new Comment(user.getId(), music.getId(), commentStr);
        // 新增评论
        Integer result = commentService.addComment(comment);
        if (result > 0) {
            try {
                // 将对应音乐存入 redis 中
                String musicKey = "music:info:" + music.getId();
                String musicnameKey = "musicName:" + music.getTitle();
                stringRedisTemplate.opsForValue().set(musicKey, objectMapper.writeValueAsString(music), Duration.ofDays(60));
                stringRedisTemplate.opsForValue().set(musicnameKey, String.valueOf(music.getId()), Duration.ofDays(60));
                log.info("getMusics, 音乐不在 redis 中存在，需要新增音乐到 redis 中：" + music);
            } catch (JsonProcessingException e) {
                log.error(e.getMessage());
            }

            return new ResponseBodyMessage<>(200, null, true);
        }

        return new ResponseBodyMessage<>(-1, "评论失败，请联系管理员", false);
    }


    @RequestMapping("/getCommentList")
    public ResponseBodyMessage<Comments> getCommentList(@RequestParam String songName, Integer page, Integer commentsPerPage) {

        if (!StringUtils.hasLength(songName)) {
            return new ResponseBodyMessage<>(-1, "歌曲名为空", null);
        }
        if (page <= 0 || commentsPerPage <= 0) {
            // 如果当前页数小于等于 0，或者每页展示数量小于等于 0，则提醒参数非法
            return new ResponseBodyMessage<>(-1, "要获取的当前评论页数或者每页展示评论数不合法", null);
        }
        // redis，根据音乐名获取音乐 ID
        String musicnameKey = "musicName:" + songName;
        String redisMusicId = stringRedisTemplate.opsForValue().get(musicnameKey);
        String redisMusicInfo = "music:info:" + redisMusicId;
        String redisMusicStr = stringRedisTemplate.opsForValue().get(redisMusicInfo);
        Music music = null;
        if (StringUtils.hasLength(redisMusicStr)) {
            try {
                music = objectMapper.readValue(redisMusicStr, Music.class);
            } catch (JsonProcessingException e) {
                log.error(e.getMessage());
            }
        } else {
            // 将音乐加入 redis 中
            music = musicService.getSongByName(songName);

            try {
                musicnameKey = "musicName:" + music.getTitle();
                redisMusicInfo = "music:info:" + music.getId();
                stringRedisTemplate.opsForValue().set(musicnameKey, String.valueOf(music.getId()));
                String redisStr = objectMapper.writeValueAsString(music);
                stringRedisTemplate.opsForValue().set(redisMusicInfo, redisStr);
                stringRedisTemplate.expire(musicnameKey, Duration.ofDays(60));
                stringRedisTemplate.expire(redisMusicInfo, Duration.ofDays(60));
            } catch (JsonProcessingException e) {

                log.error(e.getMessage());
            }

        }

        if (music == null) {
            return new ResponseBodyMessage<>(-1, "歌曲不存在", null);
        }
        Integer startIndex = (page - 1) * commentsPerPage;
        // 根据 musicId 来获取当前页的评论列表
        List<Comment> commentList = commentService.getComments(music.getId(), startIndex, commentsPerPage);
        // 获取这首歌的评论总数
        Integer totalCommentCount = commentService.getCommentCountsByMusicId(music.getId());
        // 计算总页数
        Integer totalPage = (totalCommentCount % commentsPerPage == 0) ? (totalCommentCount / commentsPerPage) : (totalCommentCount / commentsPerPage + 1);
        Comments comments = new Comments(commentList, totalPage, commentsPerPage);
        log.info("接收参数" + comments);
        return new ResponseBodyMessage<>(200, null, comments);
    }
}
